//全局变量声明
let currentPage = 1;
const pageSize = 10;
let query = 'all';
// import * as echarts from 'echarts';

//加载电影列表
function loadMovies(newQuery) {
    if (newQuery !== undefined) {
        query = newQuery;
        currentPage = 1;
    }

    $.ajax({
        url: 'index/movieList',
        method: 'GET',
        data: {
            query: query,
            pageNo: currentPage - 1,
            pageSize: pageSize
        },
        success: function(response) {
            const movieList = response.moviePages;
            const totalPages = response.total;

            $('.movie-list-detail').empty();
            movieList.forEach(movie => {
                $('.movie-list-detail').append(`
                        <li>
                            <a href="/player?movieId=${movie.movieId}" style="text-decoration: none;">
                                 <div class="movie-item">
                                    <img src="/img/movie_img/${movie.movieId}.jpg" alt="${movie.movieName}" class="movie-item-img">
                                    ${movie.vipRequire ? '<img src="/img/movie_vip.png" alt="VIP" class="vip-icon" style="position: absolute;top: 10px;right: 10px;width: 15px;height: 15px;z-index: 3;">' : ''}
                                </div>
                            </a>
                           <a href="/player?movieId=${movie.movieId}" style="text-decoration: none;">
                                <h3 class="movie-title">${movie.movieName}</h3>
                           </a>
                        </li>
                    `);
            });

            $('.current-page').text(currentPage);
            $('.total-pages').text(totalPages);
        },
        error: function(error) {
            console.log('Error fetching movies:', error);
        }
    });
}

document.addEventListener("DOMContentLoaded", function() {
    //一、图片轮播
    // 获取所有幻灯片元素
    var slides = document.querySelectorAll('.slide');
    var currentSlide = 0;

    // 显示第一张幻灯片
    slides[currentSlide].style.opacity = 1;

    // 显示下一张幻灯片的函数
    function nextSlide() {
        slides[currentSlide].style.opacity = 0;
        currentSlide = (currentSlide + 1) % slides.length;
        slides[currentSlide].style.opacity = 1;
    }

    // 设置定时器，每3秒自动显示下一张幻灯片
    var slideInterval = setInterval(nextSlide, 4000);

    //二、分类区单击选中
    // const typeItems = document.querySelectorAll("#category-list-type li");
    // const regionItems = document.querySelectorAll("#category-list-region li");
    // let selectedType="all";
    // let selectedRegion="all";
    const categoryItems = document.querySelectorAll("#category-list-type-region li");
    let selectedCategory = "all"


    function handleCategoryClick(event) {
        const items = event.currentTarget.parentElement.children;
        for (let item of items) {
            item.classList.remove("selected");
        }
        event.currentTarget.classList.add("selected");

        // 查询值
        // const newQuery = event.currentTarget.dataset.query;
        // if (event.currentTarget.parentElement.id === 'category-list-type') {
        //     selectedType = newQuery;
        // } else {
        //     selectedRegion = newQuery;
        // }
        selectedCategory = event.currentTarget.dataset.query;
        loadMovies(selectedCategory);

        // 检查是否都为 "all"
        // if (selectedType === 'all' && selectedRegion === 'all') {
        //     loadMovies('all');
        // } else {
        //     loadMovies(`${selectedType},${selectedRegion}`);
        // }
    }

    // typeItems.forEach(item => {
    //     item.addEventListener("click", handleCategoryClick);
    // });
    //
    // regionItems.forEach(item => {
    //     item.addEventListener("click", handleCategoryClick);
    // });
    categoryItems.forEach(item=>{
        item.addEventListener("click",handleCategoryClick);
    })

    // 默认选中第一个类别和地区
    // if (typeItems.length > 0) {
    //     typeItems[0].classList.add("selected");
    // }
    // if (regionItems.length > 0) {
    //     regionItems[0].classList.add("selected");
    // }
    if (categoryItems.length>0){
        categoryItems[0].classList.add("selected");
    }

    // 三、加载电影列表
    $('.prev-page').click(function() {
        if (currentPage > 1) {
            currentPage--;
            loadMovies();
        }
    });

    $('.next-page').click(function() {
        const totalPages = parseInt($('.total-pages').text());
        if (currentPage < totalPages) {
            currentPage++;
            loadMovies();
        }
    });

    loadMovies();
});

$(document).ready(function() {
    // 获取电影地区数据
    $.ajax({
        type: 'GET',
        url: '/showAreaChart', // 后端接口地址
        success: function(data) {
            var areaData = data.data;

            // 绘制电影地区饼状图
            var areaChart = echarts.init(document.getElementById('areaChart'));
            var areaOption = {
                title: {
                    text: '电影地区统计',
                    left: 'center',
                    textStyle: {
                        color: '#CDCDCD'  // 设置标题颜色
                    }
                },
                tooltip: {},
                series: [{
                    name: '电影数量',
                    type: 'pie',
                    label: {
                        color: '#ffffff',  // 设置标签颜色
                        fontSize: 14  // 设置标签字体大小
                    },
                    data: areaData.map(item => ({ value: item.areaCount, name: item.movieArea }))
                }]
            };
            areaChart.setOption(areaOption);
        },
        error: function(xhr, status, error) {
            console.error(error);
        }
    });
            // 绘制电影地区饼状图
    //         var areaChart = echarts.init(document.getElementById('areaChart'));
    //         var areaOption = {
    //             title: {
    //                 text: '电影地区统计',
    //                 left: 'center',
    //                 textStyle: {
    //                     color: '#CDCDCD'  // 设置标题颜色
    //                 }
    //             },
    //             tooltip: {
    //                 trigger: 'item',
    //                 formatter: '{b}: {c} ({d}%)'  // 显示名称、数量和百分比
    //             },
    //             series: [{
    //                 name: '电影数量',
    //                 type: 'pie',
    //                 label: {
    //                     color: '#ffffff',  // 设置标签颜色
    //                     fontSize: 14,  // 设置标签字体大小
    //                     formatter: '{b}: {c}'  // 显示名称和数量
    //                 },
    //                 data: areaData.map(item => ({ value: item.areaCount, name: item.movieArea }))
    //             }]
    //         };
    //         areaChart.setOption(areaOption);
    //     },
    //     error: function(xhr, status, error) {
    //         console.error(error);
    //     }
    // });

    // 获取电影类型数据
    $.ajax({
        type: 'GET',
        url: '/showTypeChart', // 后端接口地址
        success: function(data) {
            var typeData = data.data;

            // 绘制电影类型柱状图
            var typeChart = echarts.init(document.getElementById('typeChart'));
            var typeOption = {
                title: {
                    text: '电影类型统计',
                    left: 'center',
                    textStyle: {
                        color: '#CDCDCD'  // 设置标题颜色
                    }
                },
                xAxis: {
                    type: 'category',
                    data: typeData.map(item => item.movieType),
                    axisLabel: {
                        textStyle: {
                            color: '#ffffff'  // 设置 x 轴文字颜色
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        textStyle: {
                            color: '#ffffff'  // 设置 x 轴文字颜色
                        }
                    }
                },
                series: [{
                    name: '电影数量',
                    type: 'bar',
                    data: typeData.map(item => item.typeCount),
                    // itemStyle: {
                    //     color: '#73C0DE'  // 设置柱状颜色
                    // }
                }]
            };
            typeChart.setOption(typeOption);
        },
        error: function(xhr, status, error) {
            console.error(error);
        }
    });
});

